package com.sudao.android.candle;

import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;

import java.util.ArrayList;
import java.io.File;
import java.io.IOException;

public class MusicPlayer implements OnCompletionListener {

	private MediaPlayer mp;
	public boolean mPlaying;

	private ArrayList<String> mSongList;
	private static int mSongIndex;
	private CandleActivity mCandleActivity;

	public void setCandleActivity(CandleActivity ca) {
		mCandleActivity = ca;
	}

	public void start() {
		playMedia();
	}
	
	public void setSongList() {
		if (mCandleActivity != null)
			mSongList = mCandleActivity.mPlayList.getSongs();
	}

	public void setCurrentSong(int index) {
		if (mSongList != null && index >= mSongList.size()) {
			mSongIndex = mSongList.size() - 1;
		} 
		if (index < 0) {
			mSongIndex = 0;
		}
		mSongIndex = index;
	}

	public int getCurrentSong() {
		return mSongIndex;
	}

	public void playMedia() {
		setSongList();
		if (mSongList == null || mSongList.isEmpty())
			return;
		String filePath = mSongList.get(mSongIndex);

		//check is this song file exist
		File f = new File(filePath);
		if (!f.exists()) {
			onCompletion(mp);
		}

	    if (mp != null) {
			mp.reset();
	        try {
    	        mp.setDataSource(filePath);
  		    } catch (IOException e) {
        	}

    	    try{
        	    mp.prepare();
	        } catch(Exception e) {
    	    }
			
            mp.start();
            if (!mPlaying ) {
                mPlaying = true;
            }
            return;
        }

        if (filePath.equals("")) {
            return;
        }

		mp = new MediaPlayer();
        mp.setOnCompletionListener(this);
        mp.setAudioStreamType(2);
	
        try {
            mp.setDataSource(filePath);
        } catch (IOException e) {
        }
        try{
            mp.prepare();
        } catch(Exception e) {
        }

        mp.start();
        mPlaying = true;
	}

	public void pauseMedia() {
        if (mp != null) {
            mp.pause();
        }
        mPlaying = false;
    }

	public int getCurrentPosition() {
		if (mp != null)
			return mp.getCurrentPosition();
		return 0;
	}

	public void setCurrentPosition(int position) {
		if (mp != null)
 			mp.seekTo(position);
	}

    public void stopMedia() {
        if (mp != null) {
 			mp.stop();
        }
        mPlaying = false;
    }

    public void destroyMedia() {
        if (mp != null) {
 			mp.stop();
            mp.release();
            mp = null;
        }
        mPlaying = false;
    }

    public void resetMedia() {
        if (mp != null) {
 			mp.seekTo(0);
        }
    }

	public void onCompletion(MediaPlayer player) {
		if (!mSongList.isEmpty())
			mSongIndex = (mSongIndex + 1) % mSongList.size();
		if (mCandleActivity.mFileBrowser != null)
			mCandleActivity.mFileBrowser.refresh();
		if (mp != null)
			mp.reset();
		playMedia();
    }

}
